# -*- coding: utf-8 -*-
import hashlib
import time

try:
    from ..registry import *
except:
    from registry import *
    

async def check_sign(*args, **kwargs):
    request_sign = kwargs.get("sign")
    request_timestamp = kwargs.get("timestamp")
    
    check_sign_config = config.get("main", "check_sign")
    check_sign_config = False if check_sign_config == "false" else True
    if request_sign is None:
        if check_sign_config:
            request_sign = ""
        else:
            return
    if request_timestamp is None:
        if check_sign_config:
            request_timestamp = 0
        else:
            return
    
    # chech the timestamp
    server_timestamp = int(time.time())
    request_timestamp = float(request_timestamp)
    if request_timestamp > 158658685500:  # request_timestamp: micro second
        request_timestamp = int(request_timestamp / 1000)
    else:  # request_timestamp: second
        request_timestamp = int(request_timestamp)
    if abs(server_timestamp - request_timestamp) > 3600:
        raise Exception(f"timestamp error: {server_timestamp}, {request_timestamp}")
    
    # check the sign
    params = list(map(lambda x: str(x), args))
    params.sort()
    params_str = f"{kwargs.get('timestamp')}{'&'.join(params)}"
    params_str = params_str.encode(encoding='utf_8')
    server_sign = hashlib.md5(params_str).hexdigest().upper()
    if server_sign != request_sign:
        raise Exception(f"sign error: {server_sign}, {request_sign}")


def obj2dict(obj):
    return dict((key, obj.__dict__[key]) for key in obj.__dict__ if not key.startswith("_"))
